package com.test.utils.realm;

import com.test.po.Permission;
import com.test.po.User;
import com.test.service.PermissionService;
import com.test.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

/**
 * Created by Lenovo on 2019/1/8.
 */
public class MyRealm extends AuthorizingRealm{
    @Autowired
    private UserService userService;
    @Autowired
    private PermissionService permissionService;

    /**
     * 授权
     * 验证权限
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        User user = (User)principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // （目录+菜单+按钮）
        List<Permission> permissionList = user.getPermissionList();
        for (Permission permission : permissionList) {
            if (permission.getCode()!=null && !"".equals(permission.getCode())) {
                info.addStringPermission(permission.getCode());
            }
        }

        return info;
    }

    /**
     * 认证
     * 认证回调函数,登录时调用
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String)token.getPrincipal();
        if(username != null && !"".equals(username)){
            User user = userService.getUserByUserName(username);
            if(user != null){
                Map<String, List<Permission>> permissionMap =  permissionService.getPermissionMapByUserId(user.getId());
                user.setMenuList(permissionMap.get("menuList"));
                user.setPermissionList(permissionMap.get("permissionList"));
                return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
            }
        }
        return null;
    }
}
